<?php
namespace app\common\model;

use think\Db;

class FieldModel extends BaseModel
{

    protected $name = 'field'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    //类型自动转换
    protected $type = [
        'set'      => 'json',
        'validate' => 'json',
    ];
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    private $cmsMoudleModel;
    private $cmsMoudleCache;

    //自定义初始化
    protected function initialize()
    {
        parent::initialize();
        $this->cmsMoudleModel = new MoudleModel();
        $this->cmsMoudleCache = cache('moudle');
    }

    /*读取器*/
    protected function getIsSystemTextAttr($value, $data)
    {
        $status = [
            0 => '<span class="label label-danger">否</span>',
            1 => '<span class="label label-success">是</span>',
        ];
        return $status[$data['is_system']];
    }

    /*修改器*/
    protected function setFieldNameAttr($value)
    {
        return strtolower($value);
    }

    //不允许删除的字段
    public function noAllowDelete($mid)
    {
        $fields = $this->where('mid',$mid)->where('is_system',1)->column('field_name');
        return $fields;
    }

    /**
     * 获取验证器规则
     */
    public function getValidateRule()
    {
        $validateRule = [
            'require'     => '必填',
            'number'      => '数字',
            'float'       => '浮点数',
            'email'       => 'email',
            'date'        => '日期',
            'alpha'       => '字母',
            'alphaNum'    => '字母数字',
            'alphaDash'   => '字母数字下划线',
            'url'         => '超级链接',
            'chs'         => '汉字',
            'chsAlpha'    => '汉字字母',
            'chsAlphaNum' => '汉字字母数字',
            'chsDash'     => '汉字字母数字下划线破折号',
        ];
        return $validateRule;
    }

    /**
     * 添加字段
     */
    public function addData($data)
    {
        $table = $this->cmsMoudleModel->where('mid', $data['mid'])->value('table_name');
        $prefixTable = '`'.config('database.prefix') . $table.'`'; //带前缀主表
        $fieldName = '`'.$data['field_name'].'`'; //字段名
        $fields    = array_keys(Db::getFields($prefixTable));
        if (in_array($fieldName, $fields)) {
            exception('该字段名已存在!',40001);
        }
        try{
            switch ($data['field_type']) {
                case 'input': //文本框
                    $length = $data['set']['length'];
                    $sql    = "ALTER TABLE {$prefixTable} ADD {$fieldName} VARCHAR({$length}) NOT NULL DEFAULT '' COMMENT '{$data['title']}'";
                    $data['i_field_type'] = 'string';
                    break;
                case 'box':
                    $set    = $data['set'];
                    $length = $data['set']['length'];
                    if ($set['field_type'] == 'vachar') {
                        if (empty($length)) $length = '255';
                        $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName}  VARCHAR({$length}) NOT NULL DEFAULT '' COMMENT '{$data['title']}'";
                        $data['i_field_type'] = 'string';
                    } else {
                        if (empty($length)) $length = 4;
                        $fieldSet = " {$set['field_type']}({$length}) NOT NULL DEFAULT 0 COMMENT '{$data['title']}'";
                        $sql      = "ALTER TABLE {$prefixTable} ADD {$fieldName} {$fieldSet} ";
                        $data['i_field_type'] = 'int';
                    }
                    break;
                case 'cid':
                    $sql      = "ALTER TABLE {$prefixTable} ADD {$fieldName} int(11) unsigned NOT NULL DEFAULT '0' COMMENT '{$data['title']}'";
                    $data['i_field_type'] = 'int';
                    break;
                case 'number':
                    $set = $data['set'];
                    if ($set['field_type'] == 'decimal') {
                        $e        = isset($set['num_decimal']) ? $set['num_decimal'] : 0;
                        $fieldSet = " DECIMAL({$set['num_integer']},{$e}) NOT NULL DEFAULT 0";
                        $data['i_field_type'] = 'float';
                    } else {
                        $fieldSet = " {$set['field_type']}({$set['num_integer']}) NOT NULL DEFAULT 0";
                        $data['i_field_type'] = 'int';
                    }
                    $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName} {$fieldSet} COMMENT '{$data['title']}'";
                    break;
                case 'image':
                case 'file':
                case 'textarea':
                    $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName}  VARCHAR(255) NOT NULL DEFAULT '' COMMENT '{$data['title']}'";
                    $data['i_field_type'] = 'string';
                    break;
                case 'datetime':
                    $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName} int(10) NOT NULL DEFAULT 0 COMMENT '{$data['title']}'";
                    $data['i_field_type'] = 'date';
                    break;
                case 'editor':
                case 'files':
                case 'images':
                    $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName}  MEDIUMTEXT COMMENT '{$data['title']}'";
                    $data['i_field_type'] = 'string';
                    break;
                case "custom": //自定义
                    $fieldsql = $data['set']['fieldsql'];
                    if($fieldsql){
                        $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName} {$fieldsql} COMMENT '{$data['title']}' ";
                        $data['i_field_type'] = $fieldsql;
                    }else{
                        $sql = "";
                    }
                    break;
                default:
                    $sql    = "";
                    break;
            }
            if (!empty($sql)) {
                Db::execute($sql);
            }
            $data['table_name'] = $table;
            $this->isUpdate(false)->allowField(true)->save($data);
            return true;
        } catch (\Exception $e) {
            exception($e->getMessage(),40001);
        }
    }

    /**
     * 删除数据
     */
    public function delData($fid)
    {
        try{
            $info = $this->get($fid);
            if (!$info) {
                exception('未找到字段信息',40001);
            }
            //不允许删除字段
            if(in_array($info['field_name'],['title','cid','click','content_tpl','sort'])){
                exception('该字段不允许删除！',40001);
            }
            $prefixTable = config('database.prefix') . $info['table_name']; //表名
            $fields = array_keys(Db::getFields($prefixTable));
            if (in_array($info['field_name'], $fields)) { //先删除表字段
                $sql = "ALTER TABLE " . $prefixTable . " DROP " . $info['field_name'];
                Db::execute($sql);
            }
            $this->destroy($fid);
            return true;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }

}